package com.lzgcoding.onlineshopapp.feature.main.component

import androidx.annotation.DrawableRes
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.lzgcoding.onlineshopapp.ui.theme.Green
import com.lzgcoding.onlineshopapp.ui.theme.LargePadding
import com.lzgcoding.onlineshopapp.ui.theme.MediumPadding
import com.lzgcoding.onlineshopapp.ui.theme.SmallPadding

@Composable
fun MainBottomBar(
    @DrawableRes selected: Int,
    menus: List<Pair<Int, Int>>,
    onClick: (Int) -> Unit
) {

    val itemPositions = remember { mutableStateListOf<Triple<Int, Int, Int>>() }
    val density = LocalDensity.current
    val selectedIndex = menus.indexOfFirst { it.first == selected }.coerceAtLeast(0)
    var actualOffset by remember { mutableStateOf(0.dp) }
    var actualWidth by remember { mutableStateOf(0.dp) }
    val animatedOffset by animateDpAsState(
        targetValue = actualOffset,
        label = "indicatorOffset"
    )
    val animatedWidth by animateDpAsState(
        targetValue = actualWidth,
        label = "indicatorWidth"
    )
    val itemHeight =
        itemPositions.getOrNull(selectedIndex)?.third?.let { with(density) { it.toDp() } } ?: 0.dp

    LaunchedEffect(itemPositions.size, selectedIndex) { // 改为监听 list.size
        itemPositions.getOrNull(selectedIndex)?.let { (x, width, _) ->
            actualOffset = with(density) { x.toDp() }
            actualWidth = with(density) { width.toDp() }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(60.dp) // 调整高度
            .shadow(8.dp)
            .background(
                color = MaterialTheme.colorScheme.background
            ),
        contentAlignment = Alignment.CenterStart
    ) {
        if (itemPositions.size == menus.size && selectedIndex != -1) {
//            Log.d("TAG", "MainBottomBar: $itemHeight")
//            Log.d("TAG", "MainBottomBar: $itemPositions")
            Box(
                modifier = Modifier
                    .offset(x = animatedOffset)
                    .width(animatedWidth)
                    .height(itemHeight)
                    .navigationBarsPadding()
                    .clip(CircleShape)
                    .background(Green)
                    .padding(horizontal = LargePadding, vertical = SmallPadding)
            )
        }

        SubcomposeLayout { constraints ->
            val itemPlaceables = menus.mapIndexed { index, pair ->
                val measurable = subcompose("item_$index") {
                    MainBottomBarItem(
                        selected = pair.first == selected,
                        icon = pair.first,
                        label = pair.second,
                        onClick = {
                            onClick(pair.first)
                        }
                    )
                }.first().measure(constraints)
                measurable
            }
            val totalItemsWidth = itemPlaceables.sumOf { it.width }
            val spaceCount = menus.size + 1
            val spaceWidth = (constraints.maxWidth - totalItemsWidth).coerceAtLeast(0) / spaceCount
            itemPositions.clear()
            var xPos = spaceWidth
            itemPlaceables.forEach {
//                Log.d("TAG", "MainBottomBar: ${it.height}")
                itemPositions.add(Triple(xPos, it.width, it.height))
                xPos += it.width + spaceWidth
            }
            val maxHeight = 60.dp.roundToPx()
            layout(constraints.maxWidth, maxHeight) {
                var x = spaceWidth
                itemPlaceables.forEach {
                    it.place(x, maxHeight / 2 - it.height / 2)
                    x += it.width + spaceWidth
                }
            }
        }

    }
}

@Composable
fun MainBottomBarItem(
    selected: Boolean,
    icon: Int, label: Int,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .clip(CircleShape)
            .background(
                color = Color.Transparent
            )
            .clickable {
                onClick.invoke()
            }
            .padding(vertical = SmallPadding, horizontal = LargePadding),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(MediumPadding)
    ) {
        Image(
            painter = painterResource(icon),
            contentDescription = stringResource(label),
            modifier = Modifier.size(18.dp),
            colorFilter = ColorFilter.tint(
                if (selected) Color.White else Color.Black
            )
        )
        if (selected) {
            Text(
                text = stringResource(label),
                color = Color.White,
                style = MaterialTheme.typography.bodyMedium
            )
        }
    }
}